# feedflarexml.py
# Original Author: Amar Zumkhawala (amarzumkhawala@gmail.com)
# Project URL - http://code.google.com/p/feedflare-categories
# Distributed under Apache License 2.0
#
# $Revision: 7 $, $Date: 2008-12-28 06:00:43 +0000 (Sun, 28 Dec 2008) $
# $Author: amarzumkhawala $

from StringIO import StringIO
from atom import AtomEntry

# Our FeedFlare xml builder class
class FeedFlareXmlBuilder:
  def build(self, blogService, atomEntry):

    labels = self.labels(atomEntry)
    blogSearchByCategoryUrl = blogService.getBlogSearchByCategoryUrl(atomEntry)
   
    # ok, got through everything!  Now emit the XML 
    # for the Feedburner FeedFlare response
    feedFlareXml = StringIO()
    feedFlareXml.write("<FeedFlare>")
    # build the <Text> tag 
    feedFlareXml.write("<Text>")
    feedFlareXml.write(labels)
    feedFlareXml.write("</Text>")      
    # build the <Link> tag, if we found categories
    if len(blogSearchByCategoryUrl) > 0 :
      feedFlareXml.write("<Link href=\"")
      feedFlareXml.write(blogSearchByCategoryUrl)
      feedFlareXml.write("\"/>")
    feedFlareXml.write("</FeedFlare>")
    return feedFlareXml.getvalue()

  def labels(self, atomEntry):
    categories = atomEntry.categories()
    # build the flare text content
    labels = StringIO()
    if len(categories) >= 1 :
      # build feedflare text that shows up in the rss feed
      labels.write("Labels: ")
      for index in range(len(categories)):
        if index > 0 :
          labels.write(", ")
        labels.write(categories[index])
    return labels.getvalue()
